<template>
  <div class="share-container">
    <div class="share-card">
      <!-- Logo和标题 -->
      <div class="share-header">
        <div class="logo">
          <el-icon :size="48" color="#409eff">
            <FolderOpened />
          </el-icon>
        </div>
        <h1>文件同步器 - 文件分享</h1>
        <p class="subtitle">安全、便捷的文件分享平台</p>
      </div>

      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" :size="48" color="#409eff">
          <Loading />
        </el-icon>
        <p>加载中...</p>
      </div>

      <!-- 需要密码 -->
      <div v-else-if="requirePassword && !authenticated" class="password-container">
        <el-icon :size="64" color="#e6a23c">
          <Lock />
        </el-icon>
        <h2>此分享需要访问密码</h2>
        <p class="hint">请输入访问密码</p>

        <el-form :model="passwordForm" @submit.prevent="handleVerifyPassword" class="password-form">
          <el-form-item>
            <el-input
              v-model="passwordForm.password"
              type="password"
              placeholder="请输入访问密码"
              size="large"
              :prefix-icon="Lock"
              show-password
              @keyup.enter="handleVerifyPassword"
            />
          </el-form-item>
          <el-button type="primary" size="large" @click="handleVerifyPassword" :loading="verifying" block>
            验证密码
          </el-button>
        </el-form>
      </div>

      <!-- 文件过期或不存在 -->
      <div v-else-if="expired" class="error-container">
        <el-icon :size="64" color="#f56c6c">
          <WarningFilled />
        </el-icon>
        <h2>{{ errorMessage || '分享已失效' }}</h2>
        <p class="hint">该分享链接已过期或被取消</p>
      </div>

      <!-- 文件信息 -->
      <div v-else-if="fileInfo" class="file-info-container">
        <!-- 文件图标和名称 -->
        <div class="file-preview">
          <el-icon :size="80" :color="getFileIconColor(fileInfo.type)">
            <component :is="getFileIcon(fileInfo.type)" />
          </el-icon>
          <h2 class="file-name">{{ fileInfo.name }}</h2>
          <div class="file-meta">
            <span class="file-size">{{ formatFileSize(fileInfo.size) }}</span>
            <span class="separator">·</span>
            <span class="file-type">{{ getFileTypeText(fileInfo.type) }}</span>
          </div>
        </div>

        <!-- 分享信息 -->
        <div class="share-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="分享时间">
              {{ formatTime(fileInfo.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="有效期" v-if="fileInfo.expiry_time">
              {{ formatTime(fileInfo.expiry_time) }} 前有效
            </el-descriptions-item>
            <el-descriptions-item label="有效期" v-else>
              永久有效
            </el-descriptions-item>
            <el-descriptions-item label="下载次数">
              已被下载 {{ fileInfo.download_count || 0 }} 次
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 下载按钮 -->
        <div class="download-actions">
          <el-button
            type="primary"
            size="large"
            :icon="Download"
            @click="handleDownload"
            :loading="downloading"
            block
          >
            立即下载
          </el-button>
        </div>

        <!-- 提示信息 -->
        <div class="tips">
          <el-alert
            title="温馨提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <ul>
                <li>请确保您的网络连接稳定</li>
                <li>大文件下载可能需要较长时间，请耐心等待</li>
                <li>如遇下载失败，请刷新页面重试</li>
              </ul>
            </template>
          </el-alert>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="share-footer">
      <p>&copy; 2025 文件同步器. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  FolderOpened,
  Lock,
  Download,
  Loading,
  WarningFilled,
  Document,
  Picture,
  VideoCamera,
  Headset,
  Files,
  Folder
} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import axios from 'axios'

const route = useRoute()

// 数据状态
const loading = ref(true)
const verifying = ref(false)
const downloading = ref(false)
const requirePassword = ref(false)
const authenticated = ref(false)
const expired = ref(false)
const errorMessage = ref('')
const fileInfo = ref(null)
const shareCode = ref('')

const passwordForm = reactive({
  password: ''
})

// 生命周期
onMounted(() => {
  shareCode.value = route.params.code || route.query.code
  if (shareCode.value) {
    loadShareInfo()
  } else {
    expired.value = true
    errorMessage.value = '无效的分享链接'
    loading.value = false
  }
})

// 方法
const loadShareInfo = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/api/share/${shareCode.value}`)

    if (response.data.success) {
      const data = response.data.data

      // 检查是否需要密码
      if (data.require_password && !data.authenticated) {
        requirePassword.value = true
        authenticated.value = false
      } else {
        fileInfo.value = data.file
        authenticated.value = true
      }
    }
  } catch (error) {
    console.error('加载分享信息失败:', error)
    expired.value = true

    if (error.response?.status === 404) {
      errorMessage.value = '分享不存在或已过期'
    } else if (error.response?.status === 410) {
      errorMessage.value = '分享已失效'
    } else {
      errorMessage.value = '加载失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

const handleVerifyPassword = async () => {
  if (!passwordForm.password) {
    ElMessage.warning('请输入访问密码')
    return
  }

  verifying.value = true
  try {
    const response = await axios.post(`/api/share/${shareCode.value}/verify`, {
      password: passwordForm.password
    })

    if (response.data.success) {
      authenticated.value = true
      fileInfo.value = response.data.data.file
      ElMessage.success('验证成功')
    }
  } catch (error) {
    console.error('验证密码失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('密码错误')
    } else {
      ElMessage.error('验证失败，请稍后重试')
    }
  } finally {
    verifying.value = false
  }
}

const handleDownload = async () => {
  downloading.value = true
  try {
    const response = await axios.get(`/api/share/${shareCode.value}/download`, {
      responseType: 'blob'
    })

    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileInfo.value.name)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)

    ElMessage.success('下载开始')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  } finally {
    downloading.value = false
  }
}

// 工具函数
const getFileIcon = (type) => {
  const iconMap = {
    folder: Folder,
    image: Picture,
    video: VideoCamera,
    audio: Headset,
    document: Document
  }
  return iconMap[type] || Files
}

const getFileIconColor = (type) => {
  const colorMap = {
    folder: '#409eff',
    image: '#67c23a',
    video: '#e6a23c',
    audio: '#f56c6c',
    document: '#909399'
  }
  return colorMap[type] || '#909399'
}

const getFileTypeText = (type) => {
  const typeMap = {
    folder: '文件夹',
    image: '图片',
    video: '视频',
    audio: '音频',
    document: '文档',
    archive: '压缩包',
    code: '代码'
  }
  return typeMap[type] || '文件'
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}
</script>

<style scoped>
.share-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.share-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 600px;
  width: 100%;
  overflow: hidden;
}

.share-header {
  text-align: center;
  padding: 40px 40px 30px;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
  border-bottom: 1px solid #e9ecef;
}

.logo {
  margin-bottom: 20px;
}

.share-header h1 {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.subtitle {
  color: #6c757d;
  font-size: 14px;
  margin: 0;
}

.loading-container,
.password-container,
.error-container,
.file-info-container {
  padding: 60px 40px;
  text-align: center;
}

.loading-container p,
.error-container .hint {
  color: #6c757d;
  font-size: 16px;
  margin-top: 20px;
}

.password-container h2,
.error-container h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 30px 0 10px;
}

.hint {
  color: #6c757d;
  font-size: 14px;
  margin-bottom: 30px;
}

.password-form {
  max-width: 360px;
  margin: 0 auto;
}

.password-form .el-form-item {
  margin-bottom: 20px;
}

.file-preview {
  margin-bottom: 30px;
}

.file-name {
  font-size: 22px;
  color: #2c3e50;
  margin: 20px 0 10px;
  word-break: break-all;
}

.file-meta {
  color: #6c757d;
  font-size: 14px;
}

.separator {
  margin: 0 8px;
}

.share-info {
  margin: 30px 0;
}

.download-actions {
  margin: 30px 0;
}

.tips {
  margin-top: 30px;
}

.tips ul {
  margin: 10px 0 0 0;
  padding-left: 20px;
  text-align: left;
}

.tips li {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
}

.share-footer {
  text-align: center;
  padding: 20px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.share-footer p {
  margin: 0;
}

@media (max-width: 768px) {
  .share-card {
    margin: 0;
    border-radius: 0;
  }

  .share-header,
  .password-container,
  .error-container,
  .file-info-container {
    padding: 30px 20px;
  }
}
</style>
